/* ========== 工具 ========== */
const $ = q => document.querySelector(q);
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

/* 数字滚动 */
function animateCounter(el) {
    const target = +el.dataset.target;
    const duration = 1000;
    const step = target / (duration / 16);
    let now = 0;
    const tick = () => {
        now += step;
        if (now >= target) {
            el.textContent = target.toLocaleString();
            return;
        }
        el.textContent = Math.floor(now).toLocaleString();
        requestAnimationFrame(tick);
    };
    tick();
}

/* 全屏 */
const fullscreenBtn = document.querySelector('#fullscreenBtn');
if (fullscreenBtn) {
    fullscreenBtn.addEventListener('click', () => {
        if (document.fullscreenElement) {
            document.exitFullscreen();
        } else {
            document.documentElement.requestFullscreen().catch(err => {
                console.error('全屏请求失败:', err);
            });
        }
    });
}

/* 更新实时数据 */
function updateRealtimeData() {
    // 更新用户统计指标
    const totalUsersElement = document.querySelector('.user-stats .counter:nth-child(1)');
    const newUsersElement = document.querySelector('.user-stats .counter:nth-child(2)');
    const activeUsersElement = document.querySelector('.user-stats .counter:nth-child(3)');
    const avgTimeElement = document.querySelector('.user-stats .counter:nth-child(4)');
    
    // 更新总用户数
    if (totalUsersElement) {
        const current = parseInt(totalUsersElement.textContent.replace(/,/g, ''));
        const newValue = current + random(50, 150);
        totalUsersElement.textContent = newValue.toLocaleString();
        totalUsersElement.setAttribute('data-target', newValue);
    }
    
    // 更新新增用户
    if (newUsersElement) {
        const current = parseInt(newUsersElement.textContent.replace(/,/g, ''));
        const newValue = current + random(5, 20);
        newUsersElement.textContent = newValue.toLocaleString();
        newUsersElement.setAttribute('data-target', newValue);
    }
    
    // 更新活跃用户
    if (activeUsersElement) {
        const current = parseInt(activeUsersElement.textContent.replace(/,/g, ''));
        const newValue = current + random(-30, 80);
        activeUsersElement.textContent = newValue.toLocaleString();
        activeUsersElement.setAttribute('data-target', newValue);
    }
    
    // 更新平均使用时长
    if (avgTimeElement) {
        const current = parseInt(avgTimeElement.textContent.replace(/,/g, ''));
        const newValue = Math.max(60, current + random(-5, 10));
        avgTimeElement.textContent = newValue.toLocaleString();
        avgTimeElement.setAttribute('data-target', newValue);
    }
    
    // 更新图表数据
    if (ageChart && genderChart && regionChart) {
        // 更新地区图表数据
        const regionData = regionChart.getOption().series[0].data;
        regionData.forEach(item => {
            if (Math.random() > 0.7) {
                item.value = Math.max(0, item.value + random(-2, 5));
            }
        });
        regionChart.setOption({
            series: [{ data: regionData }]
        });
        
        // 更新年龄图表数据
        const ageData = ageChart.getOption().series[0].data;
        ageData.forEach(item => {
            if (Math.random() > 0.7) {
                item.value = Math.max(0, item.value + random(-1, 3));
            }
        });
        ageChart.setOption({
            series: [{ data: ageData }]
        });
    }
}

/* 初始化所有计数器 */
document.querySelectorAll('.counter').forEach(animateCounter);

// 每秒更新数据
setInterval(updateRealtimeData, 1000);


/* ========== 用户地域分布图 ========== */
const regionChart = echarts.init($('#regionDistributionChart'));
const regionData = [
    { name: '广东', value: 28560 },
    { name: '北京', value: 21345 },
    { name: '上海', value: 20134 },
    { name: '浙江', value: 18976 },
    { name: '江苏', value: 16543 },
    { name: '四川', value: 14321 },
    { name: '山东', value: 12987 },
    { name: '河南', value: 11543 },
    { name: '湖北', value: 10321 },
    { name: '福建', value: 9876 }
];

function initRegionChart() {
    regionChart.setOption({
        backgroundColor: 'transparent',
        grid: { left: 120, right: 20, top: 20, bottom: 20 },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: '{b}: {c}人'
        },
        xAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' }
        },
        yAxis: {
            type: 'category',
            data: regionData.map(item => item.name).reverse(),
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' }
        },
        series: [{
            type: 'bar',
            data: regionData.map(item => ({
                value: item.value,
                itemStyle: {
                    // 新的渐变色 - 不同于国家访问量图表
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#ff9a9e' },
                        { offset: 1, color: '#fad0c4' }
                    ]),
                    // 立体效果的阴影
                    shadowBlur: 10,
                    shadowColor: 'rgba(255, 154, 158, 0.5)',
                    shadowOffsetX: 5,
                    // 右侧圆角
                    borderRadius: [0, 8, 8, 0],
                    // 边框
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 1
                }
            })).reverse(),
            // 柱宽度
            barWidth: '40%',
            // 悬停效果
            emphasis: {
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#fbc2eb' },
                        { offset: 1, color: '#a6c1ee' }
                    ]),
                    shadowBlur: 20,
                    shadowColor: 'rgba(251, 194, 235, 0.7)'
                },
                // 悬停时标签动画
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{c}人',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontSize: 14,
                    // 标签出现动画
                    emphasis: {
                        animationDuration: 300
                    }
                }
            },
            // 从底部生长的动画
            animationDuration: 2000,
            animationEasing: 'cubicOut',
            animationDelay: function(idx) {
                // 倒序动画，让第一个（最高的）柱子先动
                return (regionData.length - idx) * 150;
            },
            // 点击交互
            select: {
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#d4fc79' },
                        { offset: 1, color: '#96e6a1' }
                    ]),
                    borderColor: '#fff',
                    borderWidth: 2
                }
            }
        }]
    });
}

/* ========== 用户活跃度趋势 ========== */
const activeTrendChart = echarts.init($('#activeTrendChart'));
const weekLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
const activeData = [6543, 7234, 6987, 7564, 8123, 8956, 9234];

function initActiveTrendChart() {
    activeTrendChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        grid: {
            left: 40, right: 20, top: 40, bottom: 40
        },
        xAxis: {
            type: 'category',
            data: weekLabels,
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' }
        },
        yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.05)'
                }
            }
        },
        series: [
            {
                name: '活跃用户',
                type: 'line',
                data: activeData,
                smooth: true,
                lineStyle: {
                    width: 4,
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#00d4ff' },
                        { offset: 1, color: '#0099cc' }
                    ])
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 212, 255, 0.5)' },
                        { offset: 1, color: 'rgba(0, 212, 255, 0.05)' }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                symbol: 'circle',
                symbolSize: 8,
                itemStyle: {
                    color: '#00d4ff',
                    borderColor: '#fff',
                    borderWidth: 2
                },
                markPoint: {
                    symbol: 'pin',
                    symbolSize: 40,
                    data: [
                        { type: 'max', name: '最大值' },
                        { type: 'min', name: '最小值' }
                    ],
                    label: {
                        formatter: function(params) {
                            return params.name + ': ' + params.value + '万';
                        },
                        color: '#fff'
                    }
                }
            }
        ]
    });
}

/* ========== 年龄分布 ========== */
const ageChart = echarts.init($('#ageDistributionChart'));
const ageData = [
    { value: 15, name: '18岁以下' },
    { value: 30, name: '18-25岁' },
    { value: 28, name: '26-35岁' },
    { value: 18, name: '36-45岁' },
    { value: 9, name: '45岁以上' }
];

function initAgeChart() {
    ageChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}%'
        },
        series: [
            {
                name: '年龄分布',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: 'rgba(10, 14, 39, 0.8)',
                    borderWidth: 2,
                    color: function(params) {
                        const colors = ['#00d4ff', '#ff0050', '#ffd740', '#4caf50', '#9c27b0'];
                        return colors[params.dataIndex];
                    }
                },
                label: {
                    show: true,
                    position: 'outside',
                    color: '#8892b0',
                    formatter: '{b}\n{c}%'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold',
                        color: '#fff'
                    },
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                data: ageData
            }
        ]
    });
}

/* ========== 性别分布 ========== */
const genderChart = echarts.init($('#genderDistributionChart'));
const genderData = [
    { value: 52, name: '男性', itemStyle: { color: '#00d4ff' } },
    { value: 48, name: '女性', itemStyle: { color: '#ff0050' } }
];

function initGenderChart() {
    genderChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}%'
        },
        series: [
            {
                name: '性别分布',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: 'rgba(10, 14, 39, 0.8)',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    position: 'outside',
                    color: '#8892b0',
                    formatter: '{b}\n{c}%'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold',
                        color: '#fff'
                    },
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                data: genderData
            }
        ]
    });
}

/* ========== 兴趣标签 ========== */
const interestTags = [
    { name: '数码科技', value: 85 },
    { name: '时尚美妆', value: 78 },
    { name: '美食探店', value: 72 },
    { name: '旅行摄影', value: 65 },
    { name: '健身运动', value: 60 },
    { name: '游戏电竞', value: 58 },
    { name: '家居生活', value: 55 },
    { name: '教育学习', value: 52 },
    { name: '音乐舞蹈', value: 50 },
    { name: '影视娱乐', value: 48 },
    { name: '母婴育儿', value: 45 },
    { name: '财经投资', value: 42 },
    { name: '汽车', value: 40 },
    { name: '宠物', value: 38 },
    { name: '职场', value: 35 },
    { name: '艺术设计', value: 32 },
    { name: '手工DIY', value: 30 },
    { name: '户外探险', value: 28 },
    { name: '二次元', value: 25 },
    { name: '房产', value: 22 }
];

function renderInterestTags() {
    const container = $('#interestTags');
    container.innerHTML = '';
    
    interestTags.forEach(tag => {
        const tagElement = document.createElement('div');
        tagElement.className = 'user-tag';
        tagElement.textContent = tag.name;
        tagElement.style.opacity = 0.5 + tag.value / 200;
        tagElement.style.fontSize = `${12 + tag.value / 25}px`;
        
        container.appendChild(tagElement);
    });
}

/* ========== 高价值用户列表 ========== */
const topUsers = [
    { id: 1, name: '数据分析师', avatar: 'https://randomuser.me/api/portraits/men/32.jpg', level: 'VIP', score: 9865 },
    { id: 2, name: '科技达人', avatar: 'https://randomuser.me/api/portraits/women/44.jpg', level: 'SVIP', score: 9745 },
    { id: 3, name: '时尚博主', avatar: 'https://randomuser.me/api/portraits/women/28.jpg', level: 'SVIP', score: 9632 },
    { id: 4, name: '旅行摄影师', avatar: 'https://randomuser.me/api/portraits/men/76.jpg', level: 'VIP', score: 9587 },
    { id: 5, name: '美食家', avatar: 'https://randomuser.me/api/portraits/women/19.jpg', level: 'VIP', score: 9423 },
    { id: 6, name: '游戏主播', avatar: 'https://randomuser.me/api/portraits/men/55.jpg', level: 'VIP', score: 9276 },
    { id: 7, name: '音乐人', avatar: 'https://randomuser.me/api/portraits/men/82.jpg', level: 'SVIP', score: 9134 },
    { id: 8, name: '健身教练', avatar: 'https://randomuser.me/api/portraits/women/63.jpg', level: 'VIP', score: 9021 },
    { id: 9, name: '育儿博主', avatar: 'https://randomuser.me/api/portraits/women/41.jpg', level: 'VIP', score: 8956 },
    { id: 10, name: '职场导师', avatar: 'https://randomuser.me/api/portraits/men/27.jpg', level: 'VIP', score: 8834 }
];

function renderTopUsers() {
    const container = $('#topUsersList');
    container.innerHTML = '';
    
    topUsers.forEach((user, index) => {
        const userElement = document.createElement('div');
        userElement.className = 'user-item';
        
        const levelColor = user.level === 'SVIP' ? 'linear-gradient(135deg, #ffd700, #ffa500)' : 'linear-gradient(135deg, #00d4ff, #0099cc)';
        
        userElement.innerHTML = `
            <img src="${user.avatar}" alt="${user.name}" class="user-avatar" onerror="this.src='https://via.placeholder.com/60';">
            <div class="user-info">
                <h4>${user.name}</h4>
                <p>用户ID: ${10000000 + user.id}</p>
                <div class="progress-container">
                    <div class="progress-bar" style="width: ${(user.score / 10000) * 100}%;"></div>
                </div>
            </div>
            <div class="user-stats">
                <div class="user-level" style="background: ${levelColor};">${user.level}</div>
                <div class="user-score">积分: ${user.score}</div>
            </div>
        `;
        
        // 添加动画效果
        userElement.style.opacity = '0';
        userElement.style.transform = 'translateX(-20px)';
        userElement.style.transition = 'all 0.3s ease';
        
        setTimeout(() => {
            userElement.style.opacity = '1';
            userElement.style.transform = 'translateX(0)';
        }, 100 + index * 100);
        
        container.appendChild(userElement);
    });
}

/* ========== 用户增长趋势 ========== */
const growthChart = echarts.init($('#userGrowthChart'));
const monthLabels = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
const growthData = [2345, 2890, 3120, 3560, 3890, 4230, 4670, 5120, 5890, 6540, 9230, 10560]; // 11月数据显著增加，反映购物季特点

function initGrowthChart() {
    growthChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: 40, right: 20, top: 40, bottom: 40
        },
        xAxis: {
            type: 'category',
            data: monthLabels,
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' }
        },
        yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.05)'
                }
            }
        },
        series: [
            {
                name: '累计用户',
                type: 'bar',
                data: growthData,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#00d4ff' },
                        { offset: 1, color: 'rgba(0, 212, 255, 0.3)' }
                    ])
                },
                emphasis: {
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#0099cc' },
                            { offset: 1, color: 'rgba(0, 153, 204, 0.3)' }
                        ])
                    }
                },
                animationDelay: function (idx) {
                    return idx * 100;
                }
            }
        ],
        animationEasing: 'elasticOut',
        animationDelayUpdate: function (idx) {
            return idx * 5;
        }
    });
}

/* ========== 停留时长分布 ========== */
const dwellTimeChart = echarts.init($('#dwellTimeChart'));
const dwellTimeData = [
    { name: '0-5分钟', value: 15 },
    { name: '5-15分钟', value: 25 },
    { name: '15-30分钟', value: 28 },
    { name: '30-60分钟', value: 18 },
    { name: '60-120分钟', value: 10 },
    { name: '120+分钟', value: 4 }
];

function initDwellTimeChart() {
    dwellTimeChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: 40, right: 20, top: 40, bottom: 40
        },
        xAxis: {
            type: 'category',
            data: dwellTimeData.map(d => d.name),
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { 
                color: '#8892b0',
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            name: '用户占比(%)',
            nameTextStyle: {
                color: '#8892b0'
            },
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.05)'
                }
            }
        },
        series: [
            {
                name: '停留时长',
                type: 'bar',
                data: dwellTimeData.map(d => d.value),
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#ff0050' },
                        { offset: 1, color: 'rgba(255, 0, 80, 0.3)' }
                    ]),
                    borderRadius: [4, 4, 0, 0]
                },
                emphasis: {
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#ff4081' },
                            { offset: 1, color: 'rgba(255, 64, 129, 0.3)' }
                        ])
                    }
                }
            }
        ]
    });
}

/* 更新数据 */
function updateUserData() {
    // 随机更新活跃度数据
    for (let i = 0; i < activeData.length; i++) {
        activeData[i] = Math.max(6000, Math.min(9500, activeData[i] + random(-300, 300)));
    }
    activeTrendChart.setOption({ series: [{ data: activeData }] });
    
    // 随机更新高价值用户分数
    topUsers.forEach(user => {
        user.score = Math.max(8500, Math.min(9999, user.score + random(-50, 50)));
    });
    topUsers.sort((a, b) => b.score - a.score);
    
    // 每隔一段时间更新用户列表
    if (Math.random() > 0.7) {
        renderTopUsers();
    }
}

/* 页面进入动画 */
function pageEnterAnimation() {
    const elements = document.querySelectorAll('.card');
    elements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'all 0.5s ease';
        
        setTimeout(() => {
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
        }, 100 + index * 150);
    });
}

/* 初始化页面 */
function initPage() {
    // 初始化图表
    initRegionChart();
    initActiveTrendChart();
    initAgeChart();
    initGenderChart();
    initGrowthChart();
    initDwellTimeChart();
    
    // 渲染内容
    renderInterestTags();
    renderTopUsers();
    
    // 启动定时更新
    setInterval(updateUserData, 10000);
    
    // 页面进入动画
    pageEnterAnimation();
    
    // 添加时间范围切换事件
    $('#regionTimeRange').addEventListener('change', () => {
        // 模拟数据更新
        regionChart.showLoading();
        setTimeout(() => {
            regionData.forEach(item => {
                item.value = random(100, 3500);
            });
            regionChart.setOption({ series: [{ data: regionData }] });
            regionChart.hideLoading();
        }, 500);
    });
    
    $('#activeTimeRange').addEventListener('change', () => {
        // 模拟数据更新
        activeTrendChart.showLoading();
        setTimeout(() => {
            for (let i = 0; i < activeData.length; i++) {
                activeData[i] = random(6000, 9500);
            }
            activeTrendChart.setOption({ series: [{ data: activeData }] });
            activeTrendChart.hideLoading();
        }, 500);
    });
    
    $('#userRankingType').addEventListener('change', () => {
        // 模拟数据更新
        renderTopUsers();
    });
}

// 页面加载完成后初始化
window.addEventListener('load', initPage);

/* 响应式重绘 */
window.addEventListener('resize', () => {
    regionChart.resize();
    activeTrendChart.resize();
    ageChart.resize();
    genderChart.resize();
    growthChart.resize();
    dwellTimeChart.resize();
});